<template>
	<view>
		<form @submit="submitSub" report-submit='true'>
			<view class="payment-top acea-row row-column row-center-wrapper">
				<span class="name">{{productInfo.store_name}}</span>
				<view class="pic">
					￥<span class="pic-font">{{resAmount}}</span>
				</view>
				<span class="youhui">折扣：￥{{zhekouAmount}}</span>
			</view>
			<view class="payment">
				<view class="tip">
					<view class='input'><text>￥</text><input placeholder="0.00" type='number'
							placeholder-class='placeholder' v-model="number" name="number"></input></view>
					<view class="tips-title">
						<view style="font-weight: bold; font-size: 26rpx;">提示：</view>
						<view style="margin-top: 10rpx;">当前商品为 <text
								class='font-color'>{{productInfo.store_name}}</text></view>
					</view>
					<view class="tips-box">
						<view class="tips mt-30">注意事项：</view>
						<view class="tips-samll" v-for="item in rechargeAttention" :key="item">
							{{ item }}
						</view>
					</view>
				</view>

				<view class='wrapper'>
					<view class='item'>
						<view>支付方式</view>
						<view class='list'>
							<!-- #ifdef H5 -->
							<view class='payItem acea-row row-middle' :class='active==index ?"on":""'
								@tap='payItem(index,item.pay,item.name)' v-for="(item,index) in cartArr" :key='index'
								v-if="item.payStatus==1"  v-show="index < num">
								<view class='name acea-row row-center-wrapper'>
									<view class='iconfont animated'
										:class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'>
										<image v-if="item.img" :src="item.img"
											style="display: block;width: 22px;height: 22px;border-radius: 50%;"></image>
									</view>
									{{item.name}}
								</view>
								<view class='tip'>
									{{item.title}}

								</view>
							</view>
							<view @click="reveal()" style="width: 100%;text-align: center;font-size: 14px;margin: 10px 0;" v-if="show">更多</view>
							<!-- #endif -->
							<!-- #ifdef MP || APP-PLUS -->
							<!-- <view class='payItem acea-row row-middle' :class='active==index ?"on":""' @tap='payItem(index)'
								v-for="(item,index) in cartArr" :key='index' v-if="item.payStatus==1">
								<view class='name acea-row row-center-wrapper'>
									<view class='iconfont animated'
										:class='(item.icon) + " " + (animated==true&&active==index ?"bounceIn":"")'></view>
									{{item.name}}
								</view>
								<view class='tip'>
									{{item.title}}
									<block v-if="item.value == 'balance'">
										{{parseInt(userInfo.now_money)}}
									</block>
								</view>
							</view> -->
							<!-- #endif -->
						</view>
					</view>
				</view>
				<button class='but bg-color' formType="submit">支付</button>
			</view>
		</form>
		<!-- #ifdef MP -->
		<authorize @onLoadFun="onLoadFun" :isAuto="isAuto" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		spreadInfo,
		rechargeRoutine,
		rechargeWechat,
		getRechargeApi,
		rechargeBrokerage
	} from '@/api/user.js';
	// import {
	// 	getProductDetail,
	// 	getProductCode,
	// 	collectAdd,
	// 	collectDel,

	// } from '@/api/store.js';
	import {
		// orderConfirm,
		// getCouponsOrderPrice,
		orderCreate
	} from '@/api/order.js';
	import {
		postCartAdd,
		getProductDetail,
	} from '@/api/store.js';
	import {
		toLogin
	} from '@/libs/login.js';
	import {
		mapGetters
	} from "vuex";
	// #ifdef MP
	import authorize from '@/components/Authorize';
	// #endif
	export default {
		components: {
			// #ifdef MP
			authorize
			// #endif
		},
		data() {
			let that = this;
			return {
				now_money: 0,
				navRecharge: ['账户充值', '佣金转入'],
				active: 0,
				number: '',
				num:'3',// 支付方式需要显示得我个数
				show:true, // 控制支付中更多的显示隐藏
				userinfo: {},
				placeholder: "0.00",
				from: '',
				isAuto: false, //没有授权的不会自动授权
				isShowAuth: false, //是否隐藏授权
				picList: [],
				activePic: 0,
				money: "",
				numberPic: '',
				rechar_id: 0,
				rechargeAttention: [],
				mer_id: 0,
				product_id: 0,
				productInfo: {},
				zhekou: 100,
				resAmount: '',
				zhekouAmount: '',
				cartArr: [
					// pay：0：功能未开发，1，功能已开发
					{
						"name": "微信支付",
						"icon": "icon-weixin2",
						value: 'weixin',
						title: '微信快捷支付',
						payStatus: 1,
						pay: '1'
					},
					{
						name: "支付宝支付",
						icon: "icon-zhifubao",
						// #ifdef H5		
						value: 'alipay',
						// #endif
						// #ifdef MP
						value: 'alipayQr',
						// #endif
						title: '支付宝支付',
						payStatus: 1,
						pay: '1'
					},
					{
						"name": "云闪付",
						img: require('../../../static/img/01.png'),
						value: 'chinaums',
						title: '云闪付支付',
						payStatus: 1,
						pay: '1'
					},
					{
						"name": "龙支付",
						img: require('../../../static/img/02.jpg'),
						value: 'offline',
						title: '龙支付',
						payStatus: 1,
						pay: '1'
					},
					{
						"name": "掌银支付",
						img: require('../../../static/img/03.jpg'),
						value: 'offline',
						title: '掌银支付',
						payStatus: 1,
						pay: '0'
					},
					{
						"name": "通联支付",
						img: require('../../../static/img/04.jpg'),
						value: 'offline',
						title: '通联支付',
						payStatus: 1,
						pay: '0'
					},
				],
				animated: false,
				payType: 'weixin',
				sku: ''
			};
		},
		computed: mapGetters(['isLogin']),
		onLoad(options) {
			// #ifdef H5
			this.from = this.$wechat.isWeixin() ? "wechat" : "h5"
			// #endif
			if (this.isLogin) {
				this.getUserInfo();
				// this.getRecharge();
			} else {
				// #ifdef H5 || APP-PLUS
				toLogin();
				// #endif 
				// #ifdef MP
				this.isAuto = true;
				this.$set(this, 'isShowAuth', true)
				// #endif
			}
			console.log(options);
			if (options.hasOwnProperty('mer_id')) {
				this.mer_id = options.mer_id;
			}
			if (options.hasOwnProperty('product_id')) {
				this.product_id = options.product_id;
			}
			if (this.mer_id == 0 || this.product_id == 0) {
				uni.showToast({
					title: '参数获取失败，请重新进入',
					icon: 'none'
				})
			}
			this.getGoodsDetails();
			this.getZhekou();
		},
		watch: {
			number(nVal, oVal) {
				console.log(nVal, oVal);
				if (nVal == '') {
					this.zhekouAmount=0
					this.resAmount=0
				} else {
					let zm=Math.round(nVal * this.zhekou) / 100;
					this.zhekouAmount = zm
					console.log('zhekou',this.zhekouAmount)
					this.resAmount = (nVal - zm).toFixed(2);
				}
			}
		},
		methods: {

			/**
			 * 选择金额
			 */
					// 点击显示支付方式时，显示更难多
			reveal(){
				let than = this
				than.num = '10'
				than.show = false
			},
			picCharge(idx, item) {
				this.activePic = idx;
				if (item === undefined) {
					this.rechar_id = 0;
					this.numberPic = "";
				} else {
					this.money = "";
					this.rechar_id = item.id;
					this.numberPic = item.data.price;
				}
			},


			onLoadFun: function() {
				this.isShowAuth = false;
				this.getUserInfo();
				this.getRecharge();
			},
			// 授权关闭
			authColse: function(e) {
				this.isShowAuth = e
			},
			navRecharges: function(index) {
				this.active = index;
			},
			/**
			 * 获取用户信息
			 */
			getUserInfo: function() {
				let that = this;
				spreadInfo().then(res => {
					that.$set(that, 'userinfo', res.data);
				})
			},
			/*
			 * 用户充值
			 */
			submitSub: function(e) {
				let that = this
				// 转入余额
				if (0) {

				} else {
					uni.showLoading({
						title: '正在支付',
						mask: true
					})
					// #ifdef MP || APP-PLUS
					// let money = parseFloat(this.money);
					if (this.rechar_id == 0) {
						if (parseFloat(that.money) === 0) {
							return that.$util.Tips({
								title: '充值金额金额不能为0！'
							});
						}
						if (!that.money) {
							return that.$util.Tips({
								title: '请填写充值金额！'
							});
						}
						if (!Number(that.money)) {
							return that.$util.Tips({
								title: '请填写正确的金额！'
							});
						}
					}

					rechargeWechat({
						price: that.rechar_id == 0 ? that.money : that.numberPic,
						type: 'routine',
						recharge_id: this.rechar_id
					}).then(res => {
						uni.hideLoading();
						let jsConfig = res.data.data;
						uni.requestPayment({
							timeStamp: jsConfig.timestamp,
							nonceStr: jsConfig.nonceStr,
							package: jsConfig.package,
							signType: jsConfig.signType,
							paySign: jsConfig.paySign,
							success: function(res) {
								that.$set(that, 'userinfo.now_money', that.$util.$h.Add(value, that
									.userinfo.now_money));
								return that.$util.Tips({
									title: '支付成功',
									icon: 'success'
								}, {
									tab: 5,
									url: '/pages/users/user_money/index'
								});
							},
							fail: function() {
								return that.$util.Tips({
									title: '支付失败'
								});
							},
							complete: function(res) {
								if (res.errMsg == 'requestPayment:cancel') return that.$util.Tips({
									title: '取消支付'
								});
							}
						})
					}).catch(err => {
						uni.hideLoading();
						return that.$util.Tips({
							title: err
						})
					});
					// #endif
					// #ifdef H5 

					console.log('sku', that.sku)
					let q = {
						cart_num: 1,
						is_new: 1,
						product_attr_unique: that.sku.unique,
						product_id: that.product_id,
						product_type: 0
					}
					//添加购物车
					postCartAdd(q)
						.then(res => {
							console.log('加入购物车返回', res)
							that.payment(res.data.cart_id)
						})
						.catch(res => {
							return that.$util.Tips({
								title: res
							});
						});
					// return;

					// let host = window.location.protocol + "//" + window.location.host;
					// let url = `${host}/pages/order_pay_status/index?order_id=${orderId}`
					// let eUrl = encodeURIComponent(url)
					// let locations = `${jsConfig.mweb_url}&redirect_url=${eUrl}`
					// setTimeout(() => {
					// 	location.href = locations;
					// }, 100);
					// #endif
				}
			},
			//下单支付的动作
			payment: function(cartId) {
				if(this.number==0||this.number==''||this.resAmount==0||this.resAmount==''){
					return this.$util.Tips({
						title: '请输入正确的金额'
					});
				}else if(this.number>=9999){
					return this.$util.Tips({
						title: '金额太大了！'
					});
				}
				console.log('payment')
				let data = {
					cart_id: [cartId],
					address_id: 7,
					coupon: {},
					pay_type: this.payType,
					mark: {},
					order_type: 10, // 自提订单，0是普通订单
					take: [],
					receipt_data: {},
					original_amount:this.number,
					discount_amount:this.resAmount,
					// #ifdef H5
					return_url: 'http://' + window.location.host + '/pages/users/order_list/index',
					// #endif
				};
				console.log('data', data);
				let that = this;
				orderCreate(data).then(res => {
					console.log("创建支付订单后的res", res);
					// return ;
					let status = res.data.status,
						orderId = res.data.result.order_id,
						callback_key = res.data.result.pay_key,
						jsConfig = res.data.result.config,
						goPages = '/pages/order_pay_status/index?order_id=' + orderId + '&msg=' + res.message;
					that.orderPay = true;
					switch (status) {
						case 'ORDER_EXIST':
						case 'EXTEND_ORDER':
						case 'PAY_ERROR':
						case 'error':
							uni.hideLoading();
							return that.$util.Tips({
								title: res.msg
							}, {
								tab: 5,
								url: goPages
							});
							break;
						case 'success':
							uni.hideLoading();
							if (that.BargainId || that.combinationId || that.pinkId || that.seckillId)
								return that.$util.Tips({
									title: res.msg,
									icon: 'success'
								}, {
									tab: 4,
									url: goPages
								});
							return that.$util.Tips({
								title: res.msg,
								icon: 'success'
							}, {
								tab: 5,
								url: goPages
							});
							break;
						case 'alipay':
						case "alipayQr":
							uni.hideLoading();
							this.$emit('onChangeFun', {
								action: 'payClose'
							});
							uni.navigateTo({
								url: '/pages/order_pay_back/index?keyCode=' + callback_key + '&url=' +
									jsConfig
							})
							return;
							break;
							
							// 云闪付
							case "chinaums":
								uni.hideLoading();
								
								this.$emit('onChangeFun', {
									action: 'payClose'
								});
								uni.navigateTo({
									url: '/pages/order_pay_back/index?keyCode=' + callback_key + '&url=' +
									 encodeURIComponent(jsConfig)
								})
								return;
								break;
							
							
							// #ifndef MP
						case "wechat":
						case "weixin":
							jsConfig.timeStamp = jsConfig.timestamp;
							this.$wechat.pay(jsConfig).then(res => {
								console.log('测试支付数据无效的success：' + res.data)
								return that.$util.Tips({
									title: res.message,
									icon: 'success'
								}, {
									tab: 4,
									url: goPages
								});
							}).catch(res => {
								console.log('测试支付数据无效的catch：' + res.data)
								if (res.errMsg == 'chooseWXPay:cancel') return that.$util.Tips({
									title: '取消支付'
								}, {
									tab: 5,
									url: goPages + '&status=0'
								});
							})
							break;
							// #endif
							// #ifdef MP
						case "routine":
							jsConfig.timeStamp = jsConfig.timestamp;
							that.toPay = true;
							uni.requestPayment({
								...jsConfig,
								success: function(res) {
									uni.hideLoading();
									if (that.BargainId || that.combinationId || that.pinkId || that
										.seckillId)
										return that.$util.Tips({
											title: '支付成功',
											icon: 'success'
										}, {
											tab: 4,
											url: goPages
										});
									return that.$util.Tips({
										title: '支付成功',
										icon: 'success'
									}, {
										tab: 5,
										url: goPages
									});
								},
								fail: function(e) {
									uni.hideLoading();
									let pages = '/pages/order_pay_status/index?order_id=' +
										orderId + '&msg=取消支付'
									return that.$util.Tips({
										title: '取消支付'
									}, {
										tab: 5,
										url: pages + '&status=0'
									});
								},
							})
							break;
							// #endif
						case "balance":
							uni.hideLoading();
							//余额不足
							return that.$util.Tips({
								title: res.msg
							}, {
								tab: 5,
								url: goPages + '&status=1'
							});
							break;
							// #ifdef H5
						case 'h5':
							let host = window.location.protocol + "//" + window.location.host;
							let url = `${host}/pages/order_pay_status/index?order_id=${orderId}`
							let eUrl = encodeURIComponent(url)
							let locations = `${jsConfig.mweb_url}&redirect_url=${eUrl}`
							setTimeout(() => {
								location.href = locations;
							}, 100);
							break;
							// #endif		
					}
				}).catch(err => {
					// 添加地址
					uni.hideLoading();
					return that.$util.Tips({
						title: err
					});
				});
			},


			// 获取商品详情
			getGoodsDetails: function() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let that = this;
				getProductDetail(that.product_id).then(res => {
					uni.hideLoading();
					console.log('商品详情', res)
					// if (res.data.buy_type !== 1) {
					if (false) {
						uni.showToast({
							title: '商品不能支付',
							icon: 'none'
						})
					} else {
						that.productInfo = res.data;
						if (res.data.sku) {
							console.log('sku', res.data.sku)
							let firstObjAttrFn = (data) => {
								for (let key in data) {
									return data[key];
								}
							};
							let sku = firstObjAttrFn(res.data.sku)
							if (sku) {
								that.sku = sku
							}
						} else {
							uni.showToast({
								title: '获取信息失败',
								icon: 'none'
							})
						}
					}
				}).catch(err => {
					//状态异常返回上级页面
					uni.hideLoading();
					uni.showToast({
						title: '获取商品信息失败',
						icon: 'none'
					})
				})
			},

			getZhekou: function() {
				this.zhekou = 11;
			},
			payItem: function(e, pay,name) {
				console.log(name)
				// 判断是不是建行支付，如果是建行支付，跳转到绑定银行卡也饿面
				if(name =='建设银行'){
					console.log("通过")
					uni.navigateTo({
					    url: '/pages/store/card-payment/index'
					});
					return
				}
				
				let that = this;
				let active = e;
				that.active = active;
				that.animated = true;
				if (pay == '0') {
					that.$util.Tips({
						title: '尚未完成'
					});
					return
				}
				
				that.payType = that.cartArr[active].value;
				console.log(active, 'active')
				if (that.payType == 'weixin') {
					that.payType = that.from
				}
				console.log('paytype', this.payType)

				// that.computedPrice();
				// setTimeout(function() {
				// 	that.car();
				// }, 500);
			},
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	.payment {
		position: relative;
		top: -60rpx;
		width: 100%;
		background-color: #fff;
		border-radius: 10rpx;
		padding-top: 25rpx;
		border-top-right-radius: 39rpx;
		border-top-left-radius: 39rpx;
	}

	.payment .nav {
		height: 75rpx;
		line-height: 75rpx;
		padding: 0 100rpx;
	}

	.payment .nav .item {
		font-size: 30rpx;
		color: #333;
	}

	.payment .nav .item.on {
		font-weight: bold;
		border-bottom: 4rpx solid #e83323;
	}

	.payment .input {
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 1px dashed #dddddd;
		margin: 60rpx auto 0 auto;
		padding-bottom: 20rpx;
		font-size: 56rpx;
		color: #333333;
		flex-wrap: nowrap;

	}

	.payment .input text {
		padding-left: 106rpx;
	}

	.payment .input input {
		padding-right: 106rpx;
		width: 500rpx;
		height: 94rpx;
		text-align: center;
		font-size: 70rpx;
	}

	.payment .placeholder {
		color: #d0d0d0;
		height: 100%;
		line-height: 94rpx;
	}

	.payment .tip {
		font-size: 26rpx;
		color: #888888;
		padding: 0 30rpx;
		margin-top: 25rpx;
	}

	.payment .but {
		color: #fff;
		font-size: 30rpx;
		width: 700rpx;
		height: 86rpx;
		border-radius: 50rpx;
		margin: 46rpx auto 0 auto;
		line-height: 86rpx;
	}

	.payment-top {
		width: 100%;
		height: 350rpx;
		background-color: #e83323;

		.name {
			font-size: 26rpx;
			color: rgba(255, 255, 255, 0.8);
			margin-top: -38rpx;
			margin-bottom: 30rpx;
		}

		.pic {
			font-size: 32rpx;
			color: #fff;
		}

		.pic-font {
			font-size: 78rpx;
			color: #fff;
		}
	}

	.picList {
		display: flex;
		flex-wrap: wrap;
		margin: 30rpx 0;

		.pic-box {
			width: 32%;
			height: auto;
			border-radius: 20rpx;
			margin-top: 21rpx;
			padding: 20rpx 0;
			margin-right: 12rpx;

			&:nth-child(3n) {
				margin-right: 0;
			}
		}

		.pic-box-color {
			background-color: #f4f4f4;
			color: #656565;
		}

		.pic-number {
			font-size: 22rpx;
		}

		.pic-number-pic {
			font-size: 38rpx;
			margin-right: 10rpx;
			text-align: center;
		}

		.pic-box-color-active {
			background-color: #ec3323 !important;
			color: #fff !important;
		}
	}

	.tips-box {
		.tips {
			font-size: 28rpx;
			color: #333333;
			font-weight: 800;
			margin-bottom: 14rpx;
			margin-top: 20rpx;
		}

		.tips-samll {
			font-size: 24rpx;
			color: #333333;
			margin-bottom: 14rpx;
		}

		.tip-box {
			margin-top: 30rpx;
		}
	}

	.tips-title {
		margin-top: 20rpx;
		font-size: 24rpx;
		color: #333;
	}
</style>

<style lang="scss">
	.wrapper .item .discount .placeholder {
		color: #ccc;
	}

	.wrapper {
		margin-bottom: 12rpx;
		background-color: #fff;
	}

	.wrapper .item {
		padding: 27rpx 30rpx;
		font-size: 30rpx;
		color: #282828;
	}

	.wrapper .item .discount {
		font-size: 30rpx;
		color: #999;

		&.discount_voice {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			width: 500rpx;
			text-align: right;
		}
	}

	.wrapper .item .discount .iconfont {
		color: #515151;
		font-size: 30rpx;
		margin-left: 15rpx;
	}

	.wrapper .item .discount .num {
		font-size: 32rpx;
		margin-right: 20rpx;
	}

	.wrapper .item .shipping {
		font-size: 30rpx;
		color: #999;
		position: relative;
		padding-right: 58rpx;
	}

	.wrapper .item .shipping .iconfont {
		font-size: 35rpx;
		color: #707070;
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		margin-left: 30rpx;
	}

	.wrapper .item input {
		display: flex;
		flex: 1;
		height: 100%;
		margin-left: 20rpx;
	}

	.wrapper .item .placeholder {
		color: #ccc;
	}

	.wrapper .item .list {
		margin-top: 35rpx;
	}

	.wrapper .item .list .payItem {
		border: 1px solid #eee;
		border-radius: 6rpx;
		height: 86rpx;
		width: 100%;
		box-sizing: border-box;
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #282828;
	}

	.wrapper .item .list .payItem.on {
		border-color: #fc5445;
		color: #e93323;
	}

	.wrapper .item .list .payItem .name {
		width: 50%;
		text-align: center;
		border-right: 1px solid #eee;
		justify-content: left;
		padding-left: 80rpx;
	}

	.wrapper .item .list .payItem .name .iconfont {
		width: 44rpx;
		height: 44rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 44rpx;
		// background-color: #fe960f;
		color: #fff;
		font-size: 30rpx;
		margin-right: 15rpx;
	}

	.wrapper .item .list .payItem .name .iconfont.icon-weixin2 {
		background-color: #41b035;
	}

	.wrapper .item .list .payItem .name .iconfont.icon-zhifubao {
		background-color: #4295D5;
	}

	.wrapper .item .list .payItem .tip {
		width: 49%;
		text-align: center;
		font-size: 26rpx;
		color: #aaa;
	}
</style>
